﻿using B.S.Packaged.Domain;
using B.S.Packaged.ErrorCode;
using B.S.Packaged.WebAPI.Write.Applications.Commands.CompletedStorageCommand;
using MediatR;
using SqlSugar;

namespace B.S.Packaged.WebAPI.Write.Applications.CommandHandlers.CompletedStorageHandler
{
    public class DelCompletedStorageHandler : IRequestHandler<DelCompletedStorageCommand, APIResult<int>>
    {
        private readonly ISqlSugarClient db;
        public DelCompletedStorageHandler(ISqlSugarClient db)
        {
            this.db = db;
        }
        public async Task<APIResult<int>> Handle(DelCompletedStorageCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var list = await db.Queryable<CompletedStorage>().FirstAsync(x => x.id == request.id);

            // 增加判空逻辑
            if (list == null)
            {
                result.code = APIResultCode.failed;
                result.msg = "未找到要删除的完工入库记录";
                return result;
            }

            list.IsDel = true;
            result.data = await db.Updateable<CompletedStorage>(list).ExecuteCommandAsync();
            if (result.data > 0)
            {
                result.code = APIResultCode.success;
                result.msg = "完工入库删除成功";
            }
            else
            {
                result.code = APIResultCode.failed;
                result.msg = "完工入库删除失败";
            }
            return result;
        }
    }
}
